package com.ksd1.notes;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import com.ksd1.notes.markdown.MDReader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * 展示markdown
 */
public class DisplayActivity extends BaseActivity {

    private static final String DEFAULT_DIR = Environment.getExternalStorageDirectory() + File.separator + "JNote";

    private TextView mTextView;//显示框
    private MDReader mMDReader;//读md文件
    private ScrollView mRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initVariables() {
        String content = getIntent().getExtras().getString("Content");
        mMDReader = new MDReader(content);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_display);

        //工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        mRootView = (ScrollView) findViewById(R.id.DisplayRootView);
        mTextView = (TextView) findViewById(R.id.DisplayTextView);
        mTextView.setTextKeepState(mMDReader.getFormattedContent(), TextView.BufferType.SPANNABLE);
    }

    @Override
    protected void loadData() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_display, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        Bitmap bitmap = null;
        switch (id) {
            case R.id.action_share: //分享
                bitmap = getBitmapByView(mRootView);
                Uri uri = getImageUri(savePhoto(bitmap));
                shareImage(uri, "分享图片");
                break;
            case R.id.action_photo: //保存为图片
                bitmap = getBitmapByView(mRootView);
                updatePhotoMedia(savePhoto(bitmap));
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 截取scrollview的屏幕
     * **/
    private Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取listView实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
//            scrollView.getChildAt(i).setBackgroundResource(R.drawable.bg3);
//            scrollView.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.picBg));
        }

        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);

        //保存图片
//        savePhoto(bitmap);
        return bitmap;
    }

    //保存到本地
    private File savePhoto(Bitmap bitmap){
        String fileName = System.currentTimeMillis()+".jpg";
        File photo = new File(getExternalCacheDir(),fileName);
        try {
            FileOutputStream fos = new FileOutputStream(photo);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            fos.flush();
            fos.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return photo;
    }

    //更新图库
    private void updatePhotoMedia(File file){
        //通知相册更新
        MediaStore.Images.Media.insertImage(getContentResolver(), BitmapFactory.decodeFile(file.getAbsolutePath()), file.getName(), null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);
        Toast.makeText(this, "保存成功！可到系统相册中查看！",Toast.LENGTH_SHORT).show();
    }


    /**
     * 分享图片
     * @param uri 待分享图片的uri
     * @param title 分享标题
     */
    private void shareImage(Uri uri, String title ) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.setType("image/jpeg");
        startActivity(Intent.createChooser(shareIntent, title));
    }

    private Uri getImageUri(File image){
        Uri imageUri = null;
        if(Build.VERSION.SDK_INT >= 24){
            imageUri = FileProvider.getUriForFile(this, "com.ksd1.notes.fileprovider", image);
        }else{
            imageUri = Uri.fromFile(image);
        }
        return imageUri;
    }
}
